 <template>
  <div class="warpper-box">
    <div class="inner_box">
      <div class="pass-box" :class="[isShow ? 'tree-curr':'']">
        <div class="pass-tree">
          <div class="line-ber">
            <label class="line-label">入库类别</label>
            <i v-if="!isShow" @click="isShow = true" class="el-icon-s-fold line-icon"></i>
            <i v-if="isShow" @click="isShow = false" class="el-icon-s-unfold line-icon"></i>
          </div>
          <div class="tree-prop">
            <el-input v-model="searchKey" size="small" placeholder="检索类别名称" @input="filterTree"></el-input>
              <el-tree
                :data="treeData"
                :props="treeProps"
                :current-node-key="currentKey"
                node-key="id"
                ref="treeRef"
                @node-click="handleNodeClick"
                :filter-node-method="filterNode"
                default-expand-all
                :expand-on-click-node="false"
                :render-content="renderContent"
              >
              </el-tree>
            </div>
        </div>
        <div class="pass-list">
           <el-form :inline="true" size="small" :model="formInline" ref="formInline">
              <el-form-item label="入库时间" prop="time">
                <el-date-picker
                  v-model="formInline.time"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="到期时间" prop="times">
                <el-date-picker
                  v-model="formInline.times"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="公司名称" prop="name">
                <el-input v-model="formInline.name" placeholder="公司名称"></el-input>
              </el-form-item>
              <el-form-item label="姓名" prop="contactPerson">
                <el-input
                  v-model="formInline.contactPerson"
                  placeholder="姓名"
                ></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="contactPhone">
                <el-input
                  v-model="formInline.contactPhone"
                  placeholder="电话"
                ></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formInline.email" placeholder="邮箱"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="loadList(true)">搜索</el-button>
                <el-button type="primary" icon="el-icon-setting" @click="reset('formInline')">重置</el-button>
                 <el-button type="primary" size="small" :disabled="tables.tableData.length == 0" @click="loadList(false)">5分供应商</el-button>
              </el-form-item>
            </el-form>
            <div class="psm-duo">
              <el-button type="danger" size="small" :disabled="selectItem.length == 0" @click="delBatch()">批量删除</el-button>
              <el-button type="danger" size="small" :disabled="selectItem.length == 0" @click="healerMoverPause()">移入暂停菜单</el-button>
              <el-button type="primary" size="small" :disabled="tables.tableData.length == 0" @click="dataXlsx()">导出EXCEL</el-button>
              <!-- <el-button type="danger" size="small" :disabled="selectItem.length == 0" @click="healerMoverBlacklist()">移入黑名单菜单</el-button> -->
            </div>
            <supplier-common-list
            ref="createSupplier"
            :tableData="tables.tableData" 
            :tableLabel="tables.tableLabel"
            :models="tables" 
            @on-search-click="loadList"
            @on-selection-click="selectionChange"
            @on-detail-click="supplierDetailClick"
            @on-store-detail-click="onStoreDetailClick"
            @on-remark-click="remarkClick"
            />
        </div>
      </div>
    </div>
    <supplierDetail ref="createSupplierDetail" />
    <infoStore ref="createInfoStore" />
    <el-dialog :title="tipsForm.title" :visible.sync="tipsForm.visible" width="600px" :close-on-click-modal="false">
       <el-form size="small" :model="tipsForm" label-width="100px" ref="tipsForm">
        <el-form-item label="移入类别名称">
          <el-tag v-for="item in selectItem" :key="item.id">{{ item.applyCategoryName }}</el-tag>
        </el-form-item>
        <el-form-item label="移入理由" prop="reason" :rules="[{required: true, message:'请输入移入理由', trigger: 'blur'}]">
          <el-input
            type="textarea"
            :rows="3"
            v-model="tipsForm.reason"
            placeholder="请输入移入理由"
          ></el-input>
        </el-form-item>
       </el-form>
        <div slot="footer" class="dialog-footer">
              <el-button size="small" @click="tipsForm.visible = false">取 消</el-button>
              <el-button size="small" type="primary" @click="submitAddly('tipsForm')">提交</el-button>
          </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { mapGetters, mapActions } from "vuex";
import { getSupplierStorePage, delStoreApplyBatch,getSupplierCategoryTree,supplierPause,supplierMoveBlacklist,updateStoreRemark } from "@/api/supplier_api";
import { checkEmail, checkPhone } from "@/utils/index";
import { SUPPLIER_PASS_LABEL } from "@/views/supplier/supplierModel/config";
import supplierDetail from '@/views/supplier/supplierModel/supplier_detail.vue'
import supplierCommonList from "@/views/supplier/supplierModel/supplier_common_list.vue"
import infoStore from '@/views/supplier/supplierModel/info_store.vue'
export default {
  components: {
    supplierDetail,
    supplierCommonList,
    infoStore
  },
  data() {
    return {
      formInline: {
        name: "",
        contactPerson: "",
        contactPhone: "",
        statusFlag: "",
        email: "",
        applyCategoryId:"",
        time: [],
        times:[]
      },
      currentKey:null,
      tables:{
          total:0,
          isStore:true,
          tableData: [],
          tableLabel:SUPPLIER_PASS_LABEL
        },
      models: {
        pageNum: 1,
        pageSize: 10
      },
      filteredData: [],
      treeData: [],
      treeProps: {
        label: "categoryName",
        children: "children"
      },
      selectItem: [],
      tipsForm: {
        visible: false,
       reason:'',
        callbackType:'',
        title:''
      },
      isShow:false,
      searchKey:''
    };
  },
  computed: {
    ...mapGetters(["findType"])
  },
  mounted() {
    this.getCategoryData();
     this.loadList(true);
  },
  methods: {
    async getCategoryData() {
      const { data } = await getSupplierCategoryTree();
      this.treeData = data ?? [];
      this.filteredData = data;
    },
     filterNode(value, data) {
      if (!value) return true;
      return data.categoryName.indexOf(value) !== -1;
    },
    filterTree() {
      const tree = this.$refs.treeRef;
      tree.filter(this.searchKey);
      // 递归过滤数据
      this.treeData = this.recursiveFilter(this.filteredData, this.searchKey);
    },
     // 递归过滤树数据的方法
    recursiveFilter(data, keyword) {
      return data.filter(item => {
        if (item.categoryName.includes(keyword)) {
          return true;
        }
        if (item.children && item.children.length > 0) {
          const filteredChildren = this.recursiveFilter(item.children, keyword);
          if (filteredChildren.length > 0) {
            item.children = filteredChildren;
            return true;
          }
        }
        return false;
      });
    },
    async loadList(formData) {
      let param = {};
      if (typeof formData == 'boolean') {
        this.models.pageNum = 1;
        this.models.pageSize = 10;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
        }
        if (formData == false) {
          param.totalDeduction = '5'
        }
      }
      if (typeof formData == 'object') {
         this.models.pageNum = formData.pageNum;
        this.models.pageSize = formData.pageSize;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
        }
      }
      if (
        this.formInline.contactPhone &&
        !checkPhone(this.formInline.contactPhone)
      ) {
        this.$message.error("联系电话输入格式有误");
        return;
      }
      if (this.formInline.email && !checkEmail(this.formInline.email)) {
        this.$message.error("邮箱输入格式有误");
        return;
      }
       if (this.formInline.time && this.formInline.time.length) {
        param.storeStartTime = this.formInline.time[0]
        param.storeEndTime = this.formInline.time[1]
       }

        if (this.formInline.times && this.formInline.times.length) {
        param.expireStartTime = this.formInline.times[0]
        param.expireEndTime = this.formInline.times[1]
      }
      
      param.contactPhone = this.formInline.contactPhone;
      param.email = this.formInline.email;
      param.contactPerson = this.formInline.contactPerson;
      param.name = this.formInline.name;
      param.applyCategoryId = this.formInline.applyCategoryId;
      param.pageNum = this.models.pageNum
      param.pageSize = this.models.pageSize;
      param.queryType = this.findType["pass"];
          param.tag = "1" // 供应商标签 1、合格供应商 2、暂停使用 3、黑名单
          param.storeStatus = "1" //入库状态 0.待审核 1.审核通过 2.审核拒绝
      param.isPaused = 0 // 是否暂停 1.已暂停 0.未暂停
         param.storeType = "1" // 入库类型 1、入库申请 2、更新资料
      const { code, data } = await getSupplierStorePage(param);
      if (code == 200) {
        data.list.forEach(v => {
          v.storeSupplierId = v.id
          v.id = v.applyId
        //  v.setRemark = true
        });
        this.tables.tableData = data.list
        this.tables.total = data.total
      }
    },
    reset(formName){
      this.$refs[formName].resetFields();
      this.formInline.applyCategoryId = ''
      this.loadList(true);
    },
     async dataXlsx() {
      let param = {};
      param.pageNum = 1;
      param.pageSize = this.tables.total;
          if (
        this.formInline.contactPhone &&
        !checkPhone(this.formInline.contactPhone)
      ) {
        this.$message.error("联系电话输入格式有误");
        return;
      }
      if (this.formInline.email && !checkEmail(this.formInline.email)) {
        this.$message.error("邮箱输入格式有误");
        return;
      }
       if (this.formInline.time && this.formInline.time.length) {
        param.storeStartTime = this.formInline.time[0]
        param.storeEndTime = this.formInline.time[1]
       }

        if (this.formInline.times && this.formInline.times.length) {
        param.expireStartTime = this.formInline.times[0]
        param.expireEndTime = this.formInline.times[1]
      }
      
      param.contactPhone = this.formInline.contactPhone;
      param.email = this.formInline.email;
      param.contactPerson = this.formInline.contactPerson;
      param.name = this.formInline.name;
      param.applyCategoryId = this.formInline.applyCategoryId;
        param.queryType = this.findType["pass"];
          param.tag = "1" // 供应商标签 1、合格供应商 2、暂停使用 3、黑名单
          param.storeStatus = "1" //入库状态 0.待审核 1.审核通过 2.审核拒绝
      param.isPaused = 0 // 是否暂停 1.已暂停 0.未暂停
         param.storeType = "1" // 入库类型 1、入库申请 2、更新资料
      const {code,data} = await getSupplierStorePage(param);
       if (code === 200) {
         let fields = {}
          SUPPLIER_PASS_LABEL.forEach(v => {
          if (v.type == 'on') {
            fields['index'] = v.label
          } else {
            if (v.prop) {
              fields[v.prop] = v.label
            }
          }
          })
          const entries = Object.entries(fields);
          if (entries.length > 0) {
            const firstEntry = entries.shift();
            entries.push(firstEntry);
          }
        const header = Object.fromEntries(entries);
          const manualWidthColumns = [
            { width: 10 },
            { width: 40 },
            { width: 40 },
            { width: 15 },
            { width: 15 },
            { width: 25 },
            { width: 20 },
            { width: 20 },
            { width: 50 }
          ];

        data.list.forEach((v, i) => {
          v.index = (i + 1)
          if (v.storeApplyTime) {
            let time = moment(v.storeApplyTime).format("YYYY-MM-DD");
            v.storeApplyTime = time
          }
          if (v.expireTime) {
            let time = moment(v.expireTime).format("YYYY-MM-DD");
            v.expireTime = time
          }
        })
       
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
          this.$refs.createSupplier.exportXlsx(header,data.list,manualWidthColumns,'合格列表')
        }
      }
    },
    selectionChange(arr){
        this.selectItem = arr;
      },
    delBatch() {
      if(this.selectItem.length === 0){
            return this.$message.error("请勾选要删除的数据！");
        }
        this.$confirm("确认删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          const ids = this.selectItem.map(v => v.id)
          const {code} = await delStoreApplyBatch(ids);
          if(code === 200){
            this.$message.success("操作成功");
            this.loadList(true);
          }
        }).catch(() => {});
    },
    healerMoverPause() {
      this.tipsForm.title = '移入暂停菜单'
      this.tipsForm.reason = ''
       this.tipsForm.callbackType = 'pause'
      this.tipsForm.visible = true
    },
    healerMoverBlacklist() {
      this.tipsForm.title = '移入黑名单菜单'
      this.tipsForm.reason = ''
      this.tipsForm.callbackType = 'blacklist'
      this.tipsForm.visible = true
    },
    async callApi(callbackType) {
      let p = 0;
      for (let i = 0; i < this.selectItem.length; i++){
        let item = this.selectItem[i]
        let param = {}
        param.id = item.storeSupplierId
        if (this.tipsForm.callbackType == 'pause') {
          param.pauseReason = this.tipsForm.reason
          param.storeApplicationId = item.id
        } else {
          param.blacklistReason = this.tipsForm.reason
        }
        const { code } = callbackType == 'pause' ? await supplierPause(param) : await supplierMoveBlacklist(param);
        if (code == 200) {
          p++
        }
      }
      if (p == this.selectItem.length) {
        this.$message.success('移入成功');
        this.tipsForm.visible = false
        this.loadList(true);
      }
    },
    submitAddly(formName) {
       this.$refs[formName].validate(async (valid) => {
         if (valid) {
           this.callApi(this.tipsForm.callbackType)
        }
      });
    },
    renderContent(h, { node, data }) {
      // 判断节点是否有子节点，有则为父节点，设置禁用属性
      const isDisabled = node.childNodes.length > 0;
      return h('span', {
        style: {
          color: isDisabled? '#ccc' : 'inherit'
        },
        attrs: {
          disabled: isDisabled
        }
      }, data.categoryName);
    },
    handleNodeClick(data) { 
      if (!data.children || data.children.length === 0) { 
        this.formInline.applyCategoryId = data.id
        this.loadList(true);
      }
    },
    supplierDetailClick(row) {
      this.$refs.createSupplierDetail.openDetail(row,1)
    },
     onStoreDetailClick(row) {
      this.$refs.createInfoStore.openDetail(row)
    },
    remarkClick(row) {
       this.$prompt('请输入备注', '修改备注信息', {
        confirmButtonText: '保存',
           cancelButtonText: '取消',
         inputPlaceholder: '请输入备注信息',
          beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            const value = instance.inputValue;
            const isValid = this.validateInput(value);
            if (isValid) {
              try {
                row.remarks = value
                const _isValid = await this.mockApiCall(row);
                if (_isValid) {
                  done();
                } 
              } catch (error) {
                this.$message.error('接口请求出错，请稍后重试');
              }
            } else {
              this.$message.error('请输入备注信息');
            }
          } else {
            done();
          }
        },
      }).then(() => {}).catch(() => {});
    },
    mockApiCall(result){
      return new Promise(async (resolve) => {
          const data = await updateStoreRemark(result)
          resolve(data);
      });
    },
     validateInput(value){
      return value.trim()!== '';
    }
  }
};
</script>
<style scoped>
.pass-box{
  overflow: hidden;
}
.pass-tree{
  border: 1px solid rgb(235, 238, 244);
  width: 240px;
  float: left;
  height: auto;
}
.tree-curr .pass-tree{
  width: 43px;
}
.tree-curr .line-label{
  display: none;
}
.tree-curr .tree-prop{
  display: none;
}
.line-icon{
  font-size: 24px;
  cursor: pointer;
}
.line-ber{
margin-bottom:10px;border-bottom: 1px solid #EBEEF4;padding: 0 10px;background: #fafafa;display: flex;align-items: center;
}
.line-label{
  line-height: 40px;
  flex: 1;
}
.tree-prop {
  height: calc(100vh - 208px);
  overflow: auto;
  padding: 10px;
}
.pass-list{
  margin-left: 260px;
}
.tree-curr .pass-list{
  margin-left: 63px;
}
.psm-duo{
  margin-bottom: 10px;
}
</style>
